import { ExpertSceneDetail } from '@/api/expert';
import { GetUserInfo } from '@/api/user';
import PointTag from '@/components/PointTag';
import useUserExamine from '@/hooks/useUserExamine';
import { SHARE_IMAGE } from '@/utils';
import { Button, Icon } from '@antmjs/vantui';
import { Image, RichText, Text, View } from '@tarojs/components';
import Taro, { useRouter, useShareAppMessage } from '@tarojs/taro';
import { useMemo } from 'react';
import { useRequest } from 'taro-hooks';
import { TemplateMessage } from 'types/user';
import useCustomerService from '../../components/useCustomerService';
import CutDown from '../professional/components/CutDown';
import useCode from './components/useCode';
import useDetailPopup from './components/useDetailPopup';
import useExpertsSelector from './components/useExpertsSelector';

export default function Page() {
  const { data: detail, refresh } = useRequest(
    () => ExpertSceneDetail({ sceneId: router.params?.id! }),
    {
      onSuccess: function (data) {
        data.title &&
          Taro.setNavigationBarTitle({
            title: data.title,
          });
      },
    }
  );

  //获取专家
  const experts = useMemo(() => detail?.experts, [detail]);

  const { data: user } = useRequest(GetUserInfo, {
    cacheKey: 'get:user:info',
  });

  useShareAppMessage(() => {
    return {
      title: '我发现了一个有价值的企业服务平台邀请你加入',
      imageUrl: SHARE_IMAGE,
      path: `/pages/login/share?refer_code=${user?.refer_code || ''}`,
    };
  });

  const { renderNode: renderServiceNode, open: openService } =
    useCustomerService();

  const router = useRouter();

  const { isUserExamine } = useUserExamine();

  const { renderNode: renderExportSelectorNode, open: openExportSelector } =
    useExpertsSelector({
      detail: detail!,
      onSuccess: function () {
        refresh();
      },
    });

  const { renderNode: renderDetailPopupNode, open: openDetailPopup } =
    useDetailPopup({
      detail: detail!,
      onSuccess: function () {
        refresh();
      },
    });

  //核销码
  const { renderNode: renderCodeNode, open: openCode } = useCode({
    detail: detail!,
    onClose: function () {
      refresh();
    },
  });

  return (
    <>
      <View className='bg-white min-h-screen overflow-hidden pb-32'>
        {/* head */}
        <View
          className='h-[430px] bg-cover bg-gray-400 relative overflow-hidden'
          style={{
            backgroundImage: `url(${detail?.img})`,
          }}
        ></View>
        <View className='relative ml-3 mr-3 px-6 pb-4 pt-7 shadow-lg rounded-lg mb-5 -mt-[50px] border-2 border-white bg-[rgba(255,255,255,.8)] backdrop-blur-lg'>
          {/* ?专业服务 */}
          {detail?.is_professional === 1 && (
            <View
              className='w-[100px] h-[32px] bg-cover absolute left-0 top-0'
              style={{
                backgroundImage: `url(https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/icon-activity-1.png?v=1.0.0)`,
              }}
            />
          )}

          <Text className=' block text-[36px] font-bold text-black'>
            {detail?.title}
          </Text>

          <View className=' flex items-center justify-between mt-2'>
            <PointTag value={detail?.points || 0} />

            <View className=' px-2 py-[5px] leading-none text-[16px] text-white bg-[#b8c5de] rounded-md'>
              <Text className=' font-bold text-xs'>{detail?.beans}</Text> 帮豆
            </View>
          </View>
        </View>

        <View className=' px-5'>
          {detail?.info && (
            <>
              <Text className=' text-lg text-black font-bold block mb-2'>
                服务介绍
              </Text>

              <RichText className=' text-xs leading-5' nodes={detail.info} />
            </>
          )}

          {/* {detail?.appoint_time && (
            <>
              <Text className=' text-lg text-black font-bold block mb-2 mt-4'>
                服务时间
              </Text>
              <View className='flex items-center leading-none'>
                <Icon name='clock-o' className=' text-gary4 mr-1' />
                {detail?.appoint_time}
              </View>
            </>
          )} */}

          {detail?.address && (
            <>
              <Text className=' text-lg text-black font-bold block mb-2 mt-4'>
                服务地址
              </Text>
              <View className='flex items-center leading-none'>
                <Icon name='location-o' className=' text-gary4 mr-1' />
                {detail.address}
              </View>
            </>
          )}

          <Text className=' text-lg text-black font-bold block mb-2 mt-4'>
            服务专家
          </Text>
          <View className=' flex overflow-auto space-x-2 -mx-4 pl-4'>
            {experts?.map((item) => (
              <View
                key={item.id}
                className=' flex-shrink-0 relative'
                onClick={() =>
                  Taro.navigateTo({
                    url: `/pages/professional/detail?id=${item.id}&readonly=true`,
                  })
                }
              >
                <View className='w-[208px] rounded-lg overflow-hidden'>
                  <Image
                    src={item.headimg}
                    className=' block w-full h-[208px]'
                    mode='aspectFill'
                  />
                  <View className='bg-[#F6F7FB] p-2'>
                    <Text className=' font-bold text-black text-center text-sm block van-ellipsis'>
                      {item.name}
                    </Text>
                    <Text className=' text-[20px] text-gary1 van-multi-ellipsis--l2 mt-1'>
                      {item.description}
                    </Text>
                  </View>
                </View>
              </View>
            ))}
          </View>
        </View>

        <View
          className=' fixed px-4 left-0 right-0 bottom-0 bg-white pt-2'
          style={{
            paddingBottom: ' env(safe-area-inset-bottom)',
            boxShadow: '-10px 0 10px rgba(0,0,0,.1)',
          }}
        >
          {Boolean(!detail?.order_status && detail?.order_status !== 0) && (
            <>
              <Button
                size='large'
                disabled={(user?.beans || 0) < (detail?.beans || 0)}
                type='primary'
                block
                onClick={async () => {
                  if (!user?.id)
                    return Taro.redirectTo({ url: '/pages/login/index' });

                  //@ts-ignore
                  await Taro.requestSubscribeMessage({
                    tmplIds: [
                      TemplateMessage.活动开始提醒,
                      TemplateMessage.预约结果通知,
                      TemplateMessage.积分变动提醒,
                    ],
                    success: function () {},
                    fail: function (e) {},
                  });

                  openExportSelector();
                }}
              >
                {detail?.beans}帮豆 立即预约
              </Button>
              {((user?.beans || 0) < (detail?.beans || 0) && (
                <View className=' block text-xs text-center text-gary3 mt-1'>
                  帮豆不足，（帮豆余额 {user?.beans}）
                  <Text
                    className=' text-primary font-bold'
                    onClick={async () => {
                      await isUserExamine();
                      Taro.navigateTo({
                        url: `/pages/my/bangdou/index?from=detail`,
                      });
                    }}
                  >
                    开通会员
                  </Text>
                </View>
              )) || (
                <View className=' text-xs text-gary3 text-center mt-1'>
                  预约成功核销后可获得
                  <Text className=' text-primary  font-bold'>
                    {detail?.points}
                  </Text>
                  积分
                </View>
              )}
            </>
          )}

          {Boolean(detail?.order_status === 0) && (
            <>
              {detail?.partin_time && (
                <View className=' right-2 -top-[100px] absolute z-10'>
                  <CutDown
                    value={detail?.partin_time}
                    onFinish={() => {
                      refresh();
                    }}
                  />
                </View>
              )}
              <Button
                size='large'
                type='primary'
                block
                className=' relative'
                onClick={() => openDetailPopup()}
              >
                预约待确认，可点击查看详情
              </Button>
            </>
          )}

          {detail?.order_status === 1 && (
            <>
              <Button
                size='large'
                type='primary'
                block
                onClick={() => openCode()}
              >
                <View
                  className='w-[120px] h-[120px] bg-cover absolute left-[30px] -top-[30px]'
                  style={{
                    backgroundImage: `url(https://applets-1302975996.cos.ap-nanjing.myqcloud.com/zhb/icon-success2.png)`,
                  }}
                ></View>
                预约成功，可点击查看详情
              </Button>
            </>
          )}
        </View>
      </View>

      {renderServiceNode()}
      {renderExportSelectorNode()}
      {renderDetailPopupNode()}
      {renderCodeNode()}
    </>
  );
}
